package com.rxnetwork.sample.utils.network

import com.rxnetwork.manager.RxNetWork
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import rx.Observable
import java.io.File

/**
 * xiaocode
 */
class AppNetWorkManager private constructor() {

    fun setBaseUrl(url: String): AppNetWorkManager {
        RxNetWork
                .instance
                .setBaseUrl(url)
        return this
    }

    /**
     * @param observable
     * *
     * @param listener   全状态回调
     * *
     * @param <T>
    </T> */
    fun <T> getApi(observable: Observable<T>, listener: AppNetWorkFullListener<T>) {
        baseRequest().getApi(observable, listener)
    }

    /**
     * @param observable
     * *
     * @param listener   只有成功和失败回调
     * *
     * @param <T>
    </T> */
    fun <T> getApi(observable: Observable<T>, listener: AppNetWorkListener<T>) {
        baseRequest().getApi(observable, listener)
    }

    /**
     * 多图上传

     * @param fileKey 服务端接收图片的key
     * *
     * @param files   上传文件集合
     * *
     * @param parts   上传form表单参数
     * *
     * @return
     */
    fun setUploadFiles(fileKey: String?, files: List<File>, parts: Map<String, String>): AppNetWorkManager {
        var requestBody: RequestBody
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        for (i in files.indices) {
            val file = files[i]
            if (file != null) {
                requestBody = RequestBody.create(
                        MediaType.parse("multipart/form-data"), file)
                builder?.addFormDataPart(fileKey ?: file.name, file.name, requestBody)
            }
        }
        for (entry in parts.entries) {
            if (entry != null && builder != null)
                builder.addFormDataPart(entry.key, entry.value)
        }
        multipartBody = builder?.build()
        return this
    }

    /**
     * 取消所有网络
     */
    fun clearSubscription() {
        RxNetWork.instance.clearSubscription()
    }

    private fun baseRequest(): RxNetWork {
        RxNetWork
                .instance
        return RxNetWork.instance
    }

    companion object {
        @Volatile private var singleton: AppNetWorkManager? = null

        var multipartBody: MultipartBody? = null
            private set

        val instance: AppNetWorkManager
            get() {
                if (singleton == null) {
                    synchronized(AppNetWorkManager::class.java) {
                        if (singleton == null) {
                            singleton = AppNetWorkManager()
                        }
                    }
                }
                return singleton as AppNetWorkManager
            }

        fun <T> observable(service: Class<T>): T {
            return RxNetWork
                    .instance.retrofit.create(service)
        }
    }
}
